package com.example.service;

import com.example.dao.RoleDao;
import com.example.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleService {

    @Autowired
    RoleDao roleDao;

    public List<Role> getRoles() {
        return roleDao.getRoles();
    }

    public Role getRoleById(int id) {
        Role role = roleDao.getRoleById(id);
        //填充apiIds
        List<Integer> apiIds = roleDao.getApisByRoleId(id);
        role.setApiIds(apiIds);
        return role;
    }

    @Transactional
    public void saveRole(Role role){
        System.out.println(role);
        if(role.getId() != 0){
            roleDao.updateRole(role);
            //删除roleId对应的api
            roleDao.deleteApiByRoleId(role.getId());
        }else{
            roleDao.addRole(role);
        }

        //插入roleId对应的api
        for(int apiId : role.getApiIds()){
            roleDao.addApiByRoleId(role.getId(), apiId);
        }
    }
}
